package com.sodaopen.crm.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.sodaopen.crm.common.ex.CommonException;
import com.sodaopen.crm.utils.Const;
import com.sodaopen.crm.utils.JwtUtil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;

public class JwtInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
		if(req.getMethod().equals("OPTIONS")) { //OPTIONS请求直接放行
			return true;
		}
		
		try {
			
			//1.通过请求头获取token
			String authorization = req.getHeader("Authorization");
			//2.判断请求头信息是否为空，是否“Bearer ”开头
			
			if(!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer ")) {
				String token = authorization.replace("Bearer ", "");
				Claims claims = JwtUtil.parseJwt(token);
				if(claims != null) {
					req.setAttribute(Const.LOGIN_USER, claims);
					return true;
				}
			}
		}catch (ExpiredJwtException e) {
			throw new CommonException(401, "token已过期");
		}
		
		throw new CommonException(401, "token认证失败");
	}
}
